package com.ntes.zuul;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import javax.servlet.http.HttpServletRequest;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

/**
 * 自定义路由过滤
 * Created by bjliuyue1 on 2017/5/31.
 */
@Component
public class DemoFilter extends ZuulFilter {
    private int count = 1;

    /**
     * 返回值可选：
     * pre：路由之前
     * routing：路由之时
     * post： 路由之后
     * error：发送错误调用
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    //过滤的顺序 数字越小，优先级越高
    @Override
    public int filterOrder() {
        return 0;
    }

    //是否要过滤
    @Override
    public boolean shouldFilter() {
        return (count++) % 2 == 0;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        System.out.println(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        Object accessToken = request.getParameter("token");
        if (accessToken == null) {
            System.out.println("token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            }
            catch (Exception e) {
            }
            return null;
        }
        System.out.println("ok");
        return null;
    }
}
